package xdu.lz.netty.g_handler.tcp_handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

/**
 * @Author Badribbit
 * @create 2019/4/14 21:47
 */

/**
 * 泛型是PersonProtocol，因为达到MyClientHandler已经经过decoder把字节流处理成PersonProtocol
 */
public class MyClientHandler extends SimpleChannelInboundHandler<PersonProtocol> {

    private int count = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        for (int i = 0; i < 100; i++) {
            String sendMsg = "client send!";
            PersonProtocol personProtocol = new PersonProtocol();
            personProtocol.setLength(sendMsg.getBytes().length);
            personProtocol.setContent(sendMsg.getBytes());

            ctx.writeAndFlush(personProtocol); //每调用一次进入一次encode
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception {
        int length = msg.getLength();
        byte[] content = msg.getContent();
        System.out.println("服务端接受到的数据：");
        System.out.println("长度:"+length);
        System.out.println("内容:"+new String(content,"utf8"));
        System.out.println("数量:" + (++this.count));

    }
    //异常的捕获，一般出现异常，就把连接关闭
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
